package main

import (
	"encoding/json"
	"log"

	"github.com/streadway/amqp"
)

type Target struct {
	IP   string
	Port string
}

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
	}
}

func scan(ip, port string) string {
	return "OPEN"
}

func callback(c_name string, message []byte) {

}

func main() {
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	recv_ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer recv_ch.Close()

	recv_queue, err := recv_ch.QueueDeclare(
		"send", // name
		true,   // durable
		false,  // delete when unused
		false,  // exclusive
		false,  // no-wait
		nil,    // arguments
	)
	failOnError(err, "Failed to declare a queue")

	// 每次收1个进行处理
	err = recv_ch.Qos(
		1,     // prefetch count
		0,     // prefetch size
		false, // global
	)
	failOnError(err, "Failed to set QoS")

	tasks, err := recv_ch.Consume(
		recv_queue.Name, // queue
		"",              // consumer
		false,           // auto-ack
		false,           // exclusive
		false,           // no-local
		false,           // no-wait
		nil,             // args
	)
	failOnError(err, "Failed to register a consumer")

	forever := make(chan bool)

	go func() {
		for task := range tasks {
			log.Printf("Received a message: %s", task.Body)
			var target Target
			err := json.Unmarshal(task.Body, &target)
			failOnError(err, "Wrong data format")
			if res := scan(target.IP, target.Port); res != "" {
				callback("recv", []byte(res))
			}

			task.Ack(false)
		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}
